<template>
  <div class="container" style="height: 100vh;width: 300px;padding: 20px;box-sizing: border-box;width: 100%;">
    <header>
      <MBreadcrumb :item="breadcrumbItem" />
    </header>
    <main>

      <MTitle class="title">
        <template #left>
          物流信息
        </template>
      </MTitle>
      <form>
        <table id="attributeTable" class="mtable">
          <tr class="mtr">
            <td class="field">物流单分类</td>
            <td class="value">
              <MSelect v-model="ProductInfo[0]" :options="TypeOptions" :value="ProductInfo[0]" id="ruletype" required
                style="flex: 1 1 200px;width: 100%;" @change="typeChange">
              </MSelect>
            </td>
          </tr>
          <tr class="mtr">
            <td class="field">订单标识</td>
            <td class="value">
              <MInput v-model="ProductInfo[1]" style="font-size: 12px;width: 100%" disabled></MInput>
            </td>
          </tr>
          <tr class="mtr">
            <td class="field">物流单号</td>
            <td class="value">
              <MInput v-model="ProductInfo[2]" style="font-size: 12px;width: 100%" disabled></MInput>
            </td>
          </tr>
          <tr v-for="(obj, index) in MListItem" :key="index" class="mtr">
            <td class="field">{{ obj.field }}</td>
            <td class="value">
              <MInput v-model="ProductInfo[index + 3]" style="font-size: 12px;width: 100%" v-if="!obj.disabled">
              </MInput>
              <MInput v-model="ProductInfo[index + 3]" style="font-size: 12px;width: 100%" v-if="obj.disabled" disabled>
              </MInput>
            </td>

          </tr>
          <tr class="mtr">
            <td class="field">物品数量</td>
            <td class="value">
              <MInput v-model="ProductInfo[10]" style="font-size: 12px;width: 100%" disabled></MInput>
            </td>
          </tr>
        </table>
      </form>

    </main>
    <footer>
      <div style="text-align: center;" v-if="!isDisable">
        <MButton @click="applyOrder" v-if="!isOrder">确认下单</MButton>
        <MButton @click="printOrder" v-if="isOrder">打印订单</MButton>
      </div>
    </footer>
    <MMessage v-if="toastVisible" :message="toastMessage" :state="toastState" />

  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import MBreadcrumb from "../../components/MBreadcrumb.vue"
import MTitle from "../../components/MTitle.vue"
//import MList from "../../components/MList.vue"
import MButton from "../../components/MButton.vue"
import MInput from "../../components/MInput.vue"
import MMessage from '../../components/MMessage.vue';
import MSelect from '../../components/MSelect.vue';

//import MTag from "../../components/MTag.vue"
import axios from "../../axios/axios"
export default {
  name: "LogisticsOrder",
  components: {
    MBreadcrumb,
    MTitle,
    MSelect,
    MButton,
    MInput,
    MMessage,
    //MTag
    //MIcon
  },
  setup() {
    const toastVisible = ref(false)
    const toastMessage = ref("")
    const toastState = ref("success")
    const breadcrumbItem = ref(
      {
        key: "0",
        title: '赋码管理',
        children: {
          key: "0-0",
          title: '物流信息',
        }
      })
    //const userId="12121"
    const MListItem = ref(
      [
        { "field": "发货人", },
        { "field": "发货人电话", },
        { "field": "发货地址", },
        { "field": "收件人", "disabled": true },
        { "field": "收货人电话", "disabled": true },
        { "field": "收货地址", "disabled": true },
        { "field": "物品信息", "disabled": true },
      ]
    )
    const isOrder = ref(false)
    const ProductInfo = ref(["0", "KVLEO", "", "", "", "", "", "", "", "", ""])
    const tagItems = ref([])
    const params = ref([])
    const userId = ref("")
    const orderInfo = ref({})
    const isDisable = ref(false)

    const TypeOptions = ref([
      { value: "0", text: "企业物流单" },
      { value: "1", text: "用户物流单" }
    ])
    const typeChange = () => {
      if (ProductInfo.value[0] === "0") {
        var data = [...ProductInfo.value]
        data[1] = "KVLEO"
        ProductInfo.value = data
      } else {
        var data1 = [...ProductInfo.value]
        data1[1] = "KVLUO"
        ProductInfo.value = data1
      }

    }

    const applyOrder = () => {
      if (chectValue()) {

        axios.post('/logistics/save', {
          userid: params.value.get('userId'),
          trainingid: params.value.get("trainingId"),
          logisticsnumber: ProductInfo.value[2],
          orderclass: ProductInfo.value[1],
          shipper: ProductInfo.value[3],
          shipperphone: ProductInfo.value[4],
          shipperaddress: ProductInfo.value[5],
          recipient: ProductInfo.value[6],
          recipientphone: ProductInfo.value[7],
          recipientaddress: ProductInfo.value[8],
          goodsinfo: ProductInfo.value[9],
          goodsnumber: ProductInfo.value[10],
          ordernumber: orderInfo.value.ordernumber
        })
          .then(response => {
            if (response.data.Code == "200") {
              messageShow("已下单", "success")
              isOrder.value = true

            } else {
              messageShow(response.data.Msg, "warning")
            }
          })
      }

    }
    const printOrder = () => {
      axios.get("/step/sendstep?type=printOrder&userId=" + params.value.get('userId') + "&trainingId=" + params.value.get('trainingId'))

    }
    const chectValue = () => {
      // const hasEmpty = ProductInfo.value.some(function (item, index) {
      //   if (item === "") {
      //     messageShow("请输入" + MListItem.value[index].field, "warning");
      //     return true;
      //   }
      //   return false;
      // });
      if (ProductInfo.value[3] === "") {
        messageShow("请输入" + MListItem.value[3].field, "warning");
        return false;
      }
      if (ProductInfo.value[4] === "") {
        messageShow("请输入" + MListItem.value[4].field, "warning");
        return false;
      }
      if (!(/^\d+$/.test(ProductInfo.value[4]))) {
        messageShow("请规范输入" + MListItem.value[4].field, "warning");
        return false;
      }
      if (ProductInfo.value[5] === "") {
        messageShow("请输入" + MListItem.value[5].field, "warning");
        return false;
      }
      let numValue = parseFloat(ProductInfo.value[10]);
      // 检查输入是否为数字且大于 0
      if (!(!isNaN(numValue) && numValue > 0)) {
        messageShow("数量应大于0", "warning")
        return false
      }

      return true;
    }
    const messageShow = (msg, state) => {
      toastMessage.value = msg;
      toastVisible.value = true;
      toastState.value = state
      // 使用 setTimeout 模拟 Toast 组件内部的定时器功能（仅用于演示）
      // 在实际使用中，你应该依赖 Toast 组件内部的定时器
      setTimeout(() => {
        toastVisible.value = false;
      }, 3000); // 与 Toast 组件中的 duration 属性保持一致
    }
    onMounted(() => {
      // 获取 URL 参数
      const param = new URLSearchParams(window.location.search);
      params.value = param
      if (param.has('userId')) {
        userId.value = param.get('userId');
      }
      if (param.has('isDisable')) {
        isDisable.value = param.get('isDisable') === "true"
      }
      var isPart = "1"
      if (param.get('targetPageId') === "tvLogisticsOrder") {
        isPart = "0"
      }
      axios.get('/logistics/number')
        .then(response => {
          var data = [...ProductInfo.value]
          data[2] = response.data.Data
          ProductInfo.value = data
        })
      axios.get('/order/select?userId=' + param.get('userId') + "&trainingId=" + param.get('trainingId') + "&isPart=" + isPart)
        .then(response => {
          var data = response.data.Data
          orderInfo.value = data
          var info = [...ProductInfo.value]
          info[6] = data.contactsname
          info[7] = data.contactsphone
          info[8] = data.companyaddress
          info[9] = data.productmodel
          info[10] = data.goodsnumber
          ProductInfo.value = info
        })
    });
    return {
      toastVisible,
      toastMessage,
      toastState,
      breadcrumbItem,
      MListItem,
      tagItems,
      ProductInfo,
      TypeOptions,
      isOrder,
      isDisable,
      applyOrder,
      typeChange,
      printOrder
    };
  },
};
</script>

<style scoped>
.title {
  margin-top: 30px;
}

.title1 {
  margin-top: 20px;
}

.mtr {
  display: flex;
  flex-wrap: wrap;
  /* 允许子元素换行 */
  align-items: flex-start;
}

.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

footer {
  text-align: center;
  height: 10%;
}

main {
  flex: 1;
}

.mtable {
  width: 100%;
  font-size: 13px;

}

.field {
  text-align: left;
  padding: 4px 0;
  flex: 1 1 60px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  /* 确保内容可以缩小 */
  height: 26px;
  line-height: 26px;
}

.value {
  text-align: right;
  padding: 4px 0;
  flex: 1 1 170px;
  word-break: break-word;
  /* 允许长单词换行 */
  overflow-wrap: break-word;
  min-width: 0;
  height: 26px;
  line-height: 26px;
  /* 确保内容可以缩小 */
}
</style>
